<template>
  <div class="container">
    <div class="header">
      <img src="@/assets/images/logo2.png" />
      <el-row :gutter="20" style="width: 100%">
        <el-col :span="6">
        </el-col>
        <el-col :span="6">
        </el-col>
        <el-col :span="6">
          <el-button v-if="hasJobBackground" type="success" @click="showLogs">查看任务</el-button>
          <el-button v-if="!hasJobBackground" type="info">暂无任务</el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="importDialogVisible = true">导入资料</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="content">
      <el-table :data="filterTableData" style="width: 100%">
        <el-table-column label="名称" prop="title" />
        <el-table-column label="关键字" prop="keywords" />
        <el-table-column label="简介" prop="description" />
        <el-table-column label="所在目录" prop="localpath" />
        <el-table-column label="导入时间" prop="updated_at" />
        <el-table-column align="right">
          <template #header>
            <el-input v-model="search" size="small" placeholder="搜索" />
          </template>
          <template #default="scope">
            <el-button size="small" @click="showpic(scope.row.images)">查看图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="prev, pager, next" :total="artTotal" />
      </div>
    </div>
  </div>

  <!-- 导入资料 -->
  <el-dialog v-model="importDialogVisible" title="导入资料" center>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="选择" width="80">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px"><el-checkbox v-if="!scope.row.edit" v-model="scope.row.checked"
                size="large" /></span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="路径" width="380">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span v-if="!scope.row.edit" style="margin-left: 10px">{{ scope.row.path }}</span>
            <span v-if="scope.row.edit" style="margin-left: 10px"><el-input v-model="scope.row.path" style="width: 350px;"
                placeholder="如：D:\data\upload" /></span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="right">
        <template #default="scope">
          <el-button size="small" v-if="!scope.row.edit" type="danger" @click="dirDelete(scope.$index)">删除</el-button>
          <el-button size="small" v-if="scope.row.edit" type="primary" @click="dirAdd(scope.$index)">保存</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDir">添加扫描目录</el-button>
        <el-button type="primary" @click="importSource">
          开始导入
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 任务列表 -->
  <el-dialog v-model="logsDialogVisible" title="任务列表" center>
    <div class="log-list-table">
      <el-table :data="logsData" style="width: 100%" height="400">
        <el-table-column label="事件" width="430">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="时间" width="200">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.updated_at }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="logsDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 图片列表 -->
  <el-dialog v-model="picDialogVisible" title="资源预览" center>
    <div>
      <el-image v-for="url in picurls" :key="url" :src="url" lazy />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="picDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref, h } from 'vue'
import { ElLoading, ElNotification } from 'element-plus'
import { scanPaths, delPath, addPath, itSource, scanLogs, articles } from './api/system';
import Config from "./common/config";

const search = ref('')
const artableData = ref([])
const filterTableData = computed(() =>
  artableData.value.filter(
    (data) =>
      !search.value ||
      data.title.toLowerCase().includes(search.value.toLowerCase()) ||
      data.keywords.toLowerCase().includes(search.value.toLowerCase())
  )
)

const hasJobBackground = ref(false)
const importDialogVisible = ref(false)
const logsDialogVisible = ref(false)
const picDialogVisible = ref(false)
const tableData = ref([])
const artTotal = ref(0)
const picurls = ref([])

const dirDelete = (index) => {
  let lg = ElLoading.service({ fullscreen: true })
  delPath(tableData.value[index].id)
    .then(
      res => {
        loadDirs(lg)
      }
    )
    .catch(
      e => {
        lg.close()
      }
    )
}

const dirAdd = (index) => {
  let lg = ElLoading.service({ fullscreen: true })
  addPath(tableData.value[index].path)
    .then(
      res => {
        loadDirs(lg)
      }
    )
    .catch(
      e => {
        lg.close()
      }
    )
}

const addDir = () => {
  tableData.value.push({
    path: '',
    id: '',
    edit: true,
    checked: false
  })
}

const importSource = () => {
  let paths = []
  for (let i = 0; i < tableData.value.length; i++) {
    let item = tableData.value[i]
    if (item.checked && item.id != '') {
      paths.push(item.path)
    }
  }
  console.log('paths', paths)
  itSource(paths)
    .then(
      res => {
        importDialogVisible.value = false
        logsDialogVisible.value = true
        logTimer = setInterval(function () {
          loadLogs()
        }, 500);
      }
    )
    .catch(
      e => {

      }
    )
}

const loadDirs = (lg) => {
  scanPaths()
    .then(
      res => {
        tableData.value = []
        for (var i = 0; i < res.length; i++) {
          tableData.value.push({
            path: res[i].path,
            id: res[i].id,
            edit: false,
            checked: false
          })
        }
        setTimeout(() => {
          lg.close()
        }, 1000)
      }
    )
    .catch(
      (e) => {
        setTimeout(() => {
          lg.close()
        }, 1000)
      }
    )
}

const loadLogs = () => {
  scanLogs()
    .then(
      res => {
        console.log('scanLogs', res)
        if (res.length > 0) {
          hasJobBackground.value = true
        } else {
          hasJobBackground.value = false
          clearInterval(logTimer) //关闭查询日志定时器

          loadArticles()
        }
        logsData.value = []
        for (var i = 0; i < res.length; i++) {
          let title = res[i].title
          title = title.replaceAll("\\echo.txt", "")
          logsData.value.push({
            title: title,
            updated_at: res[i].updated_at
          })
        }
      }
    ).catch(
      (e) => {

      }
    )
}

const loadArticles = () => {
  artableData.value = []
  articles()
    .then(
      res => {
        artableData.value = res
        artTotal.value = res.length
      }
    ).catch(
      (e) => {

      }
    )
}

const showLogs = () => {
  importDialogVisible.value = false
  logsDialogVisible.value = true
}

const showpic = (imgs) => {
  console.log('imgs', imgs)
  if (imgs == '') {
    ElNotification({
      title: '提示',
      message: h('i', { style: 'color: teal' }, '该资源没有设置预览图'),
    })
    return
  }
  let imgArr = imgs.split(",")
  picurls.value = imgArr.map(function (item) {
    return Config.backEndUrl + item
  })
  picDialogVisible.value = true
}

let lg = ElLoading.service({ fullscreen: true })
loadArticles()
loadDirs(lg)

const logsData = ref([])

// 定时器，查询后台时候有任务执行
var logTimer = setInterval(function () {
  loadLogs()
}, 500);


</script>

<style scoped>
.container {
  width: 1140px;
  margin: 0 auto;
}

.header {
  height: 80px;
  line-height: 80px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #dcdfe6;
}

.header img {
  width: 120px;
  height: 60px;
}

::v-deep .el-table .cell {
  white-space: pre-line;
}

.content {
  margin-top: 30px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}
</style>